package com.example.chenzhiran.myapplication7.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class appServer extends Thread{

    private ServerSocket serverSocket;
    private Socket server;
    private clientData indata;

    static final String DB_URL = "jdbc:mysql://localhost:3306/android";
    static final String USER = "root";
    static final String PASS = "mjh1995";
    Connection conn = null;
    Statement stmt = null;

    public appServer(int port) throws IOException
    {
        serverSocket = new ServerSocket(port);
    }

    public void run()
    {
        while(true)
            try {
                // 注册 JDBC 驱动打开数据库连接
                Class.forName("com.mysql.jdbc.Driver");
                System.out.println("连接数据库...");
                conn = DriverManager.getConnection(DB_URL,USER,PASS);
                stmt = conn.createStatement();

                //接收客户端连接
                server = serverSocket.accept();
                System.out.println("连接来自:" + server.getInetAddress());
                ObjectInputStream in = new ObjectInputStream(server.getInputStream());
                indata = (clientData) in.readObject();
                jumpTopage();
                in.close();
                server.close();
            } catch (Exception e ) {
                e.printStackTrace();
            }
    }

    public void jumpTopage()
    {
        switch(indata.pageId)
        {
            case 1:
                new loginPage(server, indata, stmt);
                break;
            case 2:
                new mainPage(server, indata, stmt);
                break;
            case 3:
                new productPage(server, indata, stmt);
                break;
            case 4:
                new likePage(server, indata, stmt);
                break;
            case 5:
                new purchasePage(server, indata, stmt);
                break;
            default:
                break;
        }
    }

    public static void main(String[] args)
    {
        int port = 1080;
        try
        {
            Thread t = new appServer(port);
            t.run();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
